import { ref, onMounted, onUnmounted } from 'vue'

export function useDefer(maxFrameCount = 300) {
  const frameCount = ref(0)
  let rafId: any

  function updateFrameCount() {
    frameCount.value++
    if (frameCount.value < maxFrameCount) {
      rafId = requestAnimationFrame(updateFrameCount)
    }
  }

  onMounted(() => {
    rafId = requestAnimationFrame(updateFrameCount)
  })

  onUnmounted(() => {
    cancelAnimationFrame(rafId)
  })

  return function defer(n: number) {
    return frameCount.value >= n
  }
}

export function getScreenRefreshRate(callback: (arg: number) => void, sampleCount = 10) {
  const samples: any[] = []
  let lastTimestamp:any

  function tick(timestamp: any) {
    if (lastTimestamp !== undefined) {
      const delta = timestamp - lastTimestamp
      samples.push(delta)
      if (samples.length >= sampleCount) {
        const averageDelta = samples.reduce((a, b) => a + b) / samples.length
        const fps = 1000 / averageDelta
        callback(Math.round(fps))
        return
      }
    }
    lastTimestamp = timestamp
    requestAnimationFrame(tick)
  }

  // 确保页面可见时测量
  if (document.visibilityState === 'visible') {
    requestAnimationFrame(tick)
  } else {
    const onVisibilityChange = () => {
      if (document.visibilityState === 'visible') {
        document.removeEventListener('visibilitychange', onVisibilityChange)
        requestAnimationFrame(tick)
      }
    }
    document.addEventListener('visibilitychange', onVisibilityChange)
  }
}
